package cn.com.lms.business.exam.web;

import cn.com.lms.app.api.exam.vo.PaperSubjectVO;
import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.exam.enums.PaperTypeEnum;
import cn.com.lms.business.exam.enums.QuickScoreTypeEnum;
import cn.com.lms.business.exam.enums.SubjectTypeEnum;
import cn.com.lms.business.exam.persistence.entity.*;
import cn.com.lms.business.exam.service.*;
import cn.com.lms.business.exam.web.vo.PaperDetailVO;
import cn.com.lms.business.exam.web.vo.PaperListVO;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import com.bnzj.cloud.business.core.persistence.entity.SysUser;

import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;

import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;

import com.bnzj.core.util.BeanUtils;
import com.bnzj.core.util.FbConstant;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.hibernate.internal.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author zhangzhenjiang
 * @createDate 2020/3/14
 * @description
 */
@Tag(name = "试卷", description = "试卷管理")
@RestController
@RequestMapping("/exam/paper")
public class PaperController {

    @Autowired
    PaperService paperService;

    @Autowired
    PaperQuestionService paperQuestionService;
    @Autowired
    PaperSubjectService paperSubjectService;

    @Autowired
    PaperExtraService paperExtraService;

    @Operation(summary = "分页查询", description = "",
            parameters = {@Parameter(name = "keyWord", description = "关键子查询，题库名称进行模糊查询", allowEmptyValue = true,
                    allowReserved = true, schema = @Schema(implementation = String.class, description = "keyWord")), @Parameter(name = "type", description = "出题方式", allowEmptyValue = true,
                    allowReserved = true, schema = @Schema(implementation = Short.class, description = "type")),
                    @Parameter(name = "creator", description = "创建人id", allowEmptyValue = true,
                            allowReserved = true, schema = @Schema(implementation = Long.class, description = "creator")),
                    @Parameter(name = "isEnable", description = "0-未启用 1-已启用", allowEmptyValue = true,
                            allowReserved = true, schema = @Schema(implementation = Long.class, description = "isEnable")),
                    @Parameter(name = "limit", description = "分页大小", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "分页大小")),
                    @Parameter(name = "offset", description = "页码", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "页码")),

            })
    @GetMapping(value = "/page")
    public ResponseResult<Page<PaperListVO>> getPaperPage(HttpServletRequest request) {
        Long creator = StringHelper.isNotEmpty(request.getParameter("creator")) ? Long.parseLong(request.getParameter("creator")) : null;
        Short type = StringHelper.isNotEmpty(request.getParameter("type")) ? Short.parseShort(request.getParameter("type")) : null;
        String keyWord = request.getParameter("keyWord");
        String isEnable = request.getParameter("isEnable");

        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "p.create_time"));
        QueryHelpBean queryHelpBean = PaperService.getPaperListVOQueryHelpBean();
        queryHelpBean.setPageable(pageable);
        //试卷名称，模糊搜索

        IExpression andCondition1 = CompareExpression.build("p.is_delete", CompareType.equal, false);
        queryHelpBean.addWhere(andCondition1);
        if (StringHelper.isNotEmpty(keyWord)) {
            IExpression orCondition2 = CompareExpression.build("p.paper_name", CompareType.like, keyWord);
            queryHelpBean.addWhere(orCondition2);
        }
        if(StringHelper.isNotEmpty(isEnable)){
            IExpression andCondition5 = CompareExpression.build("p.is_enable", CompareType.equal, isEnable);
            queryHelpBean.addWhere(andCondition5);
        }
        if (type != null) {
            IExpression andCondition3 = CompareExpression.build("p.type", CompareType.equal, type);
            queryHelpBean.addWhere(andCondition3);
        }
        if (creator != null) {
            IExpression andCondition4 = CompareExpression.build("p.creator", CompareType.equal, creator);
            queryHelpBean.addWhere(andCondition4);
        }
        Page<PaperListVO> all = paperService.findAll(queryHelpBean);

        return ResponseResult.success(all);
    }

    @Operation(summary = "根据id查询")
    @GetMapping("/one/{id}")
    public ResponseResult<PaperDetailVO> getById(@Parameter(name = "id", description = "主键", required = true) @PathVariable("id") Long id) {
        Optional<Paper> paperOpt = paperService.findById(id);
        if (!paperOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        Paper paper = paperOpt.get();
        PaperDetailVO paperDetailVO = new PaperDetailVO();
        Integer paperSingleCount = 0;
        Integer paperMultipleCount = 0;
        Integer paperJudgeCount = 0;

        BeanUtils.copyProperties(paper, paperDetailVO);
        PaperExtra paperExtra = paperExtraService.findByPaperId(paper.getId());

        if (PaperTypeEnum.FIXED_SELECTION.getValue().equals(paper.getType())) {
            // 查询试卷试题
            List<Map<String, Object>> questionSubjectList = paperSubjectService.findQuestionSubjectByPaperId(paper.getId());
            // 试卷单选、多选、判断题的题数统计
            if (!CollectionUtils.isEmpty(questionSubjectList)) {
                paperSingleCount = questionSubjectList.stream().filter(m -> SubjectTypeEnum.SINGLE_OPTION.getValue().toString().equals(m.get("type").toString())).collect(Collectors.toList()).size();
                paperMultipleCount = questionSubjectList.stream().filter(m -> SubjectTypeEnum.MULTIPLE_OPTION.getValue().toString().equals(m.get("type").toString())).collect(Collectors.toList()).size();
                paperJudgeCount = questionSubjectList.stream().filter(m -> SubjectTypeEnum.JUDGE.getValue().toString().equals(m.get("type").toString())).collect(Collectors.toList()).size();

            }
            paperDetailVO.setQuestionSubjectList(questionSubjectList);

        }
        if (PaperTypeEnum.RANDOM_QUESTION.getValue().equals(paper.getType())) {
            // 查询试卷题库
            // [{"singleCount":"12","multipleCount":"12","judgeCount":null},{"singleCount":"12","multipleCount":"12","judgeCount"1"}]

//            List<bnz_exam_paper_question>
            List<Map> questionList = paperSubjectService.findQuestionByPaperId(paper.getId());
            // 试卷单选、多选、判断题的题数统计
            if (!CollectionUtils.isEmpty(questionList)) {
                // [12,12]  [12,12]  [0,1]
                List<Integer> singleCountList = new CopyOnWriteArrayList<>();
                List<Integer> multipleCountList = new CopyOnWriteArrayList<>();
                List<Integer> judgeCountList = new CopyOnWriteArrayList<>();
                questionList.stream().forEach(map -> {
                    Integer singleCount = map.get("singleCount") != null ? Integer.valueOf(map.get("singleCount").toString()) : 0;
                    Integer multipleCount = map.get("multipleCount") != null ? Integer.valueOf(map.get("multipleCount").toString()) : 0;
                    Integer judgeCount = map.get("judgeCount") != null ? Integer.valueOf(map.get("judgeCount").toString()) : 0;
                    singleCountList.add(singleCount);
                    multipleCountList.add(multipleCount);
                    judgeCountList.add(judgeCount);
                });
                if (!CollectionUtils.isEmpty(singleCountList)) {
                    // [12,12] 12+12 =24
                    paperSingleCount = singleCountList.stream().collect(Collectors.summingInt(Integer::intValue));
                }
                if (!CollectionUtils.isEmpty(multipleCountList)) {
                    paperMultipleCount = multipleCountList.stream().collect(Collectors.summingInt(Integer::intValue));
                }
                if (!CollectionUtils.isEmpty(judgeCountList)) {
                    paperJudgeCount = judgeCountList.stream().collect(Collectors.summingInt(Integer::intValue));
                }
            }
            paperDetailVO.setQuestionList(questionList);
        }
        // 试卷单选、多选、判断题总数
        paperDetailVO.setPaperSingleCount(paperSingleCount);
        paperDetailVO.setPaperMultipleCount(paperMultipleCount);
        paperDetailVO.setPaperJudgeCount(paperJudgeCount);
        // 试卷总分，试题总数
        if (paperExtra != null) {
            paperDetailVO.setTotalPaperScore(paperExtra.getPaperScore());
            paperDetailVO.setTotalSubjectCount(paperExtra.getSubjectCount());
        }


        return ResponseResult.success(paperDetailVO);
    }


    @Operation(summary = "保存")
    @PostMapping("/save")
    public ResponseResult<?> addPaper(@RequestBody Paper paper) {
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        paper.setCreator(String.valueOf(sysUser.getId()));
        paper.setCreateTime(new Date());
        paper.setCreatorName(sysUser.getCname());
        paper.setIsDelete(false);
        paper.setIsEnable(false);
        paperService.addPaper(paper);
        return ResponseResult.success();
    }


    @Operation(summary = "更新")
    @PostMapping("/update")
    public ResponseResult<?> updatePaper(@RequestBody Paper paper) {
        System.out.println(paper.getId());
        Optional<Paper> paperOpt = paperService.findById(paper.getId());
        if (!paperOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        paper.setModifyTime(new Date());
        paper.setCreator(String.valueOf(sysUser.getId()));
        paper.setCreateTime(new Date());
        paper.setCreatorName(sysUser.getCname());
        Paper target = paperOpt.get();
        paperService.updatePaper(paper, target);
        return ResponseResult.success();
    }


    @Operation(summary = "根据id复制")
    @GetMapping("/copy/{id}")
    public ResponseResult<Paper> copyById(@Parameter(in = ParameterIn.PATH, name = "id", description = "主键", required = true) @PathVariable("id") Long id) {

        Optional<Paper> papertOpt = paperService.findById(id);
        if (!papertOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        Paper source = papertOpt.get();

        Paper paper = new Paper();
        BeanUtils.copyProperties(source, paper);
        paper.setPaperName("(复制)" + paper.getPaperName());
        paper.setId(0L); // 0
        Paper result = paperService.addPaper(paper);
        return ResponseResult.success(paper);
    }


    @Operation(summary = "删除，批量删除", description = "根据分类id删除试题")
    @PostMapping("/delete")
    public ResponseResult<Integer> deleteById(@RequestBody List<Long> id) {
        Integer count = paperService.updateIsDelete(true, id);
        return ResponseResult.success(count);

    }


    @Operation(summary = "启用", description = "根据分类id启用试卷")
    @PostMapping("/enable")
    public ResponseResult<Integer> enableById(@RequestBody List<Long> id) {
        Integer count = paperService.updateIsEnable(true, id);
        return ResponseResult.success(count);

    }

    @Operation(summary = "禁用", description = "根据分类id禁用试卷")
    @PostMapping("/disable")
    public ResponseResult<Integer> disableById(@RequestBody List<Long> id) {
        Integer count = paperService.updateIsEnable(false, id);
        return ResponseResult.success(count);

    }

    @Operation(summary = "获取试卷总分", description = "根据ids获取试卷总分")
    @PostMapping("/getPaperScoreByIdList")
    public ResponseResult<List<Map>> getPaperScoreByIdList(@RequestBody List<Long> paperIdList) {
        List<Map> map = paperService.getPaperScoreByIdList(paperIdList);
        return ResponseResult.success(map);

    }

    @Operation(summary = "获取随机试题", description = "根据试卷id获取获取随机试题")
    @GetMapping("/getRandQuestionSubjectByPaperId")
    public ResponseResult<List<PaperSubjectVO>> getRandQuestionSubjectByPaperId(@RequestParam("paperId") Long paperId) {
        List<PaperSubjectVO> paperSubjectVOList = paperSubjectService.findRandQuestionSubjectByPaperId(paperId);
        return ResponseResult.success(paperSubjectVOList);

    }


}
